package com.system.exam.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.exam.admin.core.http.Result;
import com.system.exam.admin.entity.SysMenu;
import com.system.exam.admin.service.SysMenuService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sys/menu")
@Api(tags = "系统菜单")
public class SysMenuController {


    @Autowired
    SysMenuService sysMenuService;

    /**
     * 系统菜单树
     */
    @GetMapping("/treeList")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public Result TreeList() {
        Map<String, Object> result = new HashMap<>();
        result.put("treeMenu", sysMenuService.buildTreeMenu(sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num")), true));
        return Result.success(result);
    }

    @GetMapping("/treeListNoButtons")
    @PreAuthorize("hasAuthority('system:menu:list')")
    public Result treeListNoButtons() {
        Map<String, Object> result = new HashMap<>();
        result.put("treeMenu", sysMenuService.buildTreeMenu(sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num")), false));
        return Result.success(result);
    }

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:menu:add')" + "||" + "hasAuthority('system:menu:edit')")
//    @AutoLog("新增菜单或编辑菜单")
    public Result saveMenu(@RequestBody SysMenu sysMenu) {
        if (sysMenu.getId() < 0) {
            Date d = new Date();
            sysMenu.setCreateTime(d);
            sysMenu.setUpdateTime(d);
            sysMenuService.save(sysMenu);
        } else {
            sysMenu.setUpdateTime(new Date());
            sysMenuService.updateById(sysMenu);
        }
        return Result.success();
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:menu:query')")
//    @AutoLog("获取菜单信息")
    public Result getMenuIds(@PathVariable Long id) {

        return Result.success(sysMenuService.getById(id));
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:menu:delete')")
//    @AutoLog("删除菜单")
    public Result deleteMenu(@RequestBody SysMenu sysMenu) {
        System.out.println("getID:" + sysMenu.getId());
        long count = sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", sysMenu.getId()));
        if (count == 0) {
            sysMenuService.removeById(sysMenu.getId());
        } else {
            return Result.error("请删除子菜单");
        }
        return Result.success();
    }
}
